package com.tengju.user.domain.model.survey;

import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

public class SurveyConfig {

    private SurveyId surveyId;

    private SurveyMeta surveyMeta;

    List<SurveyQuestionConfig> questionConfigList;

    public SurveyConfig(SurveyMeta surveyMeta) {
        this.surveyId = surveyMeta.getId();
        this.surveyMeta = surveyMeta;
    }

    public void addQuestionConfigList(List<SurveyQuestionConfig> questionConfigList) {
        if (CollectionUtils.isEmpty(questionConfigList)) {
            this.questionConfigList = new ArrayList<>();
            return;
        }
        this.questionConfigList = questionConfigList;
        ThreadLocalRandom localRandom = ThreadLocalRandom.current();
        if (needShuffle()) {
            this.questionConfigList = this.questionConfigList.stream()
                    .sorted(Comparator.comparingInt( v -> localRandom.nextInt()))
                    .collect(Collectors.toList());
        }
        if (questionLimit() > 0) {
            this.questionConfigList = this.questionConfigList.stream()
                    .limit(questionLimit())
                    .collect(Collectors.toList());
        }
    }

    public SurveyId getSurveyId() {
        return surveyId;
    }

    public String getSurveyTitle() {
        if (surveyMeta == null) {
            return null;
        }
        return surveyMeta.getTitle();
    }

    public String getSurveyDesc() {
        if (surveyMeta == null) {
            return null;
        }
        return surveyMeta.getDesc();
    }

    public boolean needShuffle() {
        if (surveyMeta == null) {
            return false;
        }
        return SurveyShuffleStatusEnum.SHUFFLE.equals(surveyMeta.getShuffle());
    }

    public Integer questionLimit() {
        if (surveyMeta == null) {
            return 0;
        }
        return surveyMeta.getItemNumLimit();
    }

    public List<SurveyQuestionConfig> getQuestionConfigList() {
        return questionConfigList;
    }


}
